<template>
  <!-- 主页面，其它页面在里面对应渲染 -->
  <div class="layout-wrapper layout-row">
    <v-sidebar v-if="navShow" class="app-sidebar" :nav="navList" />
    <div class="layout-wrapper">
      <v-header class="app-header" @switch-role="loginIndexDataFn" />
      <div class="app-body">
        <!-- 面包屑公共组件 -->
        <breadcrumb v-if="usePublicBreadcrumbFlag" />
        <v-main class="app-main" :class="usePublicBreadcrumbFlag ? '' : 'noMarginAndPadding'" />
      </div>
    </div>
  </div>
</template>
<script>
  // @ is an alias to /src
  import header from "../components/layout/header.vue";
  import sidebar from "../components/layout/sidebar.vue";
  import main from "@/components/layout/main.vue";
  import { mapActions } from "vuex";
  import { loginIndexData, witnessItemRuleGetTime } from "../api/api";
  export default {
    name: "Home",
    components: {
      "v-header": header,
      "v-main": main,
      "v-sidebar": sidebar
    },
    data() {
      return {
        // managerFlag: sessionStorage.getItem("userType"),
      };
    },
    // 监听属性 类似于data概念
    computed: {
      navShow() {
        return this.$route.meta.sidebarShow;
      },
      route() {
        return this.$route;
      },
      // navList() {
      //   return this.$store.getters.routerArr;
      // },
      navList() {
        let navArr = [];
        const { routerArr } = this.$store.getters;
        if (routerArr && routerArr[0] && routerArr[0].children) {
          navArr = routerArr[0].children;
        }
        return navArr;
      },
      // 判断是否使用公共的面包屑样式（true：是，false：否）。
      usePublicBreadcrumbFlag() {
        /* 以下模块由于特殊样式，均需要自定义面包屑样式
        1. 系统管理-用户管理
        2. 见证任务管理-查看见证资料（见证报告）
        2. 见证任务管理-新增见证任务
        3. 见证记录审核-审核见证记录
        4. 见证任务查看-查看见证资料
        5. 操作日志-见证日志-查看操作日志
        6. 见证工作台（管理员账号的路由：/WitnessTaskManagement/WitnessTable，见证员账号路由：/Workbench）
        */
        const pathArr = [
          "/UserManagement",
          "/WitnessTaskManagement/ViewingWitnessData",
          "/WitnessTaskManagement/AddWitnessTask",
          "/ViewingWitnessRecords",
          "/ViewingWitnessData",
          "/WitnessLogController/WitnessLogControllerOperate",
          "/WitnessTaskManagement/WitnessTable",
          "/Workbench",
          "/WitnessTask/Attachment",
          "/WitnessTaskManagement/Attachment",
          "/FilingHandover/detail",
          '/WitnessTask/WitnessReport',
          "/witness-location",
          "/wintessquery/trajectoryXmDetail",
          "/wintessquery/trajectoryPerDetail",
          "/wintessquery/wangerDetail"
        ]; // 不需要公共面包屑组件的数组
        return pathArr.indexOf(this.$route.path) === -1;
      }
    },
    watch: {},
    beforeDestroy() {
      // 销毁ws连接
      this.$websocket.dispatch("websocket_disconnect");
      clearInterval(window.setIntervalFlag);
      this.websocketCloseFn();
    },
    async created() {
      if (process.env.VUE_APP_Dev === "not_login") {
        await this.setHeadNavAction(this.$store.getters.routerArrNotLogin);
      } else {
        // 正式路由（调用接口）
        await this.loginIndexDataFn();
      }
      if (!window.setIntervalFlag) {
        this.witnessItemRuleGetTimeFn();
      }
      clearInterval(window.setIntervalFlag);
      window.setIntervalFlag = setInterval(() => {
        this.witnessItemRuleGetTimeFn();
      }, 5000);
      setTimeout(() => {
        this.initStomp();
      }, 500);
    },
    mounted() {
      // 待定netty接口 by link
      this.$websocketNettyPend.dispatch("websocketInit", "pend");
      // const timeDiv = document.createElement("div");
      // document.body.appendChild(timeDiv);
      // clearInterval(window.intervalWebsocket);
      // window.intervalWebsocket = setInterval(() => {
      //   console.log("setInterval", "timeDiv");
      //   timeDiv && timeDiv.click();
      // }, 1000 * 10);
    },
    methods: {
      ...mapActions([
        "switchIdentity",
        "setSystemAction",
        "setButtonListAction",
        "setHeadNavAction" // 将 `this.setHeadNavFn(amount)` 映射为 `this.$store.dispatch('setHeadNavFn', amount)`
      ]),
      websocketCloseFn() {
        console.log("websocketCloseFn");
        clearTimeout(this.closeFlag);
        this.closeFlag = setTimeout(() => {
          this.$websocketNettyPend.dispatch("websocketClose", "pend");
        }, 500);
      },
      // 初始化stomp实时通信的链接
      initStomp() {
        console.log("全局sock");
        // return;
        const wsUrl = `${process.env.VUE_APP_API}/stomp`;
        // const wsUrl = "http://10.0.204.143:8888/gdw/stomp";
        this.$websocket.dispatch("websocket_init", wsUrl);
      },
      toUrl() {
        this.$router.go(-1);
        // this.$router.replace({
        //   name: "ManageList",
        // });
      },
      async witnessItemRuleGetTimeFn() {
        // await witnessItemRuleGetTime();
        try {
          await witnessItemRuleGetTime();
        } catch (error) {
          console.warn(error);
        }
      },
      async loginIndexDataFn() {
        try {
          const params = {
            systemCode: "WITNESS_SYSTEM"
          };
          const res = await loginIndexData(params);
          // console.log("loginIndexData", res);
          if (res.code === 0) {
            // console.log("this.setHeadNavAction", this.setHeadNavAction);
            // 见证系统所有角色roleCode
            const systemCodes = ["GDW_R_WITNESS_MANAGER", "GDW_R_WITNESS_PERSON", "GDW_R_WITNESS_SUPER"];
            if (!systemCodes.includes(res.data.currentIdentify.roleCode)) {
              const currentIdentify = res.data.identifyList.find((identify) => systemCodes.includes(identify.roleCode));
              if (currentIdentify) {
                const isSwitchSuccess = await this.switchIdentity({
                  identityId: currentIdentify.id
                });
                if (isSwitchSuccess) {
                  this.loginIndexDataFn();
                }
              } else {
                this.$message.error("您没有权限进入该系统");
                return this.$router.push({
                  name: "Login"
                });
              }
            }
            await this.setSystemAction({
              username: res.data.userName,
              userid: res.data.userId,
              systemname: res.data.systemName,
              identifyList: res.data.identifyList,
              roleCode: res.data.currentIdentify.roleCode,
              roleName: res.data.currentIdentify.roleName
            });
            await this.setHeadNavAction(res.data.menuList);
            await this.setButtonListAction(res.data.buttonList);
            console.log("this.$route.path111111111111", this.$route);
            sessionStorage.setItem("userId", res.data.userId);
            if (this.$route.path === "/") {
              console.log("this.$route.path看看");
              console.log("this.$route.path", res.data.menuList[0].children[0].path);
              await this.$router.replace({
                path: res.data.menuList[0].children[0].path
              });
            }
            console.log("this.$route", this.$route);
          } else {
            this.$message({
              message: "获取系统数据失败",
              type: "error",
              duration: 1000,
              onClose: () => {
                // 左侧导航登录时跳转 和 刷新导航不变用到
                // sessionStorage.default_num = 1;
                // sessionStorage.default_system = "";
                // let loadPath = sysInfo.requestPath;
                // debugger;
                // window.location.href = loadPath;
                this.$router.push({
                  name: "Login"
                });
              }
            });
          }
        } catch (e) {
          console.warn(e);
          //   this.$message({
          //     message: "登录初始化失败",
          //     type: "error",
          //     // iconClass: "el-icon-error"
          //     duration: 2000,
          //     onClose: () => {
          //       this.$router.push({
          //         name: "Login",
          //       });
          //     },
          //   });
        }
      },
      isIncludePath(menus) {
        const { path } = this.$route;
        const pathArr = [
          {
            children: menus,
            isRoot: true
          }
        ];
        // eslint-disable-next-line prefer-destructuring
        let current = menus[0];
        let i = 0;
        while (current) {
          if (current.children && current.children.length > 0) {
            pathArr.push(current);
            // eslint-disable-next-line prefer-destructuring
            current = current.children[0];
            i = 0;
          } else if (path === current.path) {
            return true;
          } else {
            i++;
            if (i >= pathArr[pathArr.length - 1].children.length) {
              if (pathArr.length > 1) {
                current = pathArr.pop();
                i = pathArr[pathArr.length - 1].children.indexOf(current);
              } else {
                return false;
              }
            } else {
              current = pathArr[pathArr.length - 1].children[i];
            }
          }
        }
      }
    }
  };
</script>
<style lang="scss" scoped>
  .breadcrumb {
    padding: 5px 15px;
    background: #fff;
    // color: #333;
    font-weight: bold;
    font-size: 14px;
    line-height: 34px;
  }
  .noMarginAndPadding {
    margin: 0 !important;
    padding: 0 !important;
    background-color: #eee !important;
  }
</style>
